package kisti.module.tierServer;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import kisti.module.Notification.Notification;
import kisti.module.database.ConnectToKissmanDB;
import kisti.module.log.Glog;
import kisti.module.server.ConnectToGridServer;





/**
 * <pre>
 * kisti.module.tierServer
 *   |_ TierServer.java
 *
 * </pre>
 *
 * Desc : Client 로 부터의 모든 요청을 받아서 해당 결과를 돌려준다. 
 * 
 * @Company : KISTI
 * @Author :daniel
 * @Date   :2011. 10. 26. 오후 3:30:12
 * @Version:
 *
 */

public class TierServer implements Runnable{

	public static final int PORT = 8197;
//	public static final String IPADDR = "150.183.234.167";
	public ConnectToGridServer moduleServer;	
	public ServerSocket serverSocket=null;
		
	
	/**
	 * 
	 * Desc : Constructor of TierServer.java class
	 */
	public TierServer() {
		// TODO Auto-generated constructor stub
		
		moduleServer = new ConnectToGridServer();
		
		try {
			serverSocket = new ServerSocket(PORT);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();			
		}
		
		Thread t = new Thread(this);
		t.start();
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
	
		try {
			while (true) {					
	
				Socket sock = serverSocket.accept();				
				Glog.Log(Glog.LOG_USERACCESS,"TierServer" ,sock.getInetAddress().toString());
				
				
				Glog.Log(Glog.LOG_COMMON,"TierServer" ,"--------- accept ----------");				
				try {
					BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
					String requestService = in.readLine();

					Glog.Log(Glog.LOG_COMMON,"TierServer" ,"cleintRequests: "+ requestService);

					Object obj = null;
					
					if (requestService.substring(0, 3).equals("DB_")) {//디비요청
						ConnectToKissmanDB kissmanDB = new ConnectToKissmanDB();
						obj = kissmanDB.requestDataToDataBase("nothing....");
						sendXMLDataToClient(obj, sock);
					}else if(requestService.substring(0, 4).equals("URL_")){ //URL 요청
						
						String URL ="http://vobox02.sdfarm.kr/pbswebmon/pbswebmon-ce03/cgi-bin/graph.py?start=-24h";						
						String sendImageName = "ceGraphImage.bmp";
						CeMonGraph cm = new CeMonGraph();
						String imgUrl = cm.getImageUrl(URL);
						if (!cm.downloadImage(imgUrl , sendImageName)) {
							System.out.println("Download Error");
						}				
						
						sendImgDataToClient(sendImageName, sock);
						
												
					}else if(requestService.substring(0,4).equals("DEMO") ){
						
						System.out.println("DEMO<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<+"+requestService.substring(0,4));
						Notification nf = new Notification();						
						if (requestService.equals("DEMO_Email")) {
							nf.sender_email("Test message from G-main Tierserver !!!");
							System.out.println("DEMO_Email");
						} else if(requestService.equals("DEMO_SMS")){
							nf.sender_sms("Test message from G-main Tierserver !!!");
							System.out.println("DEMO_SMS");
						}
						

					}else{ // kissman server 요청						
						obj = moduleServer.requestDataToServer(requestService);
						sendXMLDataToClient(obj, sock);						
					}
					
				} catch (Exception e) {
					// TODO: handle exception
					Glog.Log(Glog.LOG_ERROR,"TierServer" , e.toString());
				}finally{					
					sock.close();					
					Glog.Log(Glog.LOG_COMMON,"TierServer" ,"---------- socket close ------------ ");
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			Glog.Log(Glog.LOG_ERROR,"TierServer" , e.toString());
		}
	}
	
	
	/**
	 * 
	 * Desc : 클라이언트로 GraphImage 전송 
	 * @Method Name : sendImgDataToClient
	 * @param fileName 전송할 이미지의 경로
	 * @param sock 이미지를 보낼 클라이언트의 정보가 담긴 소켓 
	 *
	 */	
	public void sendImgDataToClient(String fileName, Socket sock){		
		
		try {
			Glog.Log(Glog.LOG_COMMON,"sendImgDataToClient" ,"---------- start sendImage ------------ ");
			File imgFile = new File(fileName);
			FileInputStream fis = new FileInputStream(imgFile);
			OutputStream os = sock.getOutputStream();
			
						
			byte[] buffer = new byte[1024];
			while (fis.available() > 0) {
				int readSize = fis.read(buffer);
				os.write(buffer,0,readSize);
			}			
			fis.close();
			os.close();
			sock.close();
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Glog.Log(Glog.LOG_ERROR,"sendImgDataToClient" , e.toString());
		}		
	}	
	
	/**
	 * 
	 * Desc : 클라이언트로 XML 데이터 전송
	 * @Method Name : sendDataToClient
	 * @param sendData 서버들에서 가져온 XML 파일들
	 * @param sock 이미지를 보낼 클라이언트의 정보가 담긴 소켓 
	 *
	 */
	public void sendXMLDataToClient(Object sendData, Socket sock){
		ObjectOutputStream oos=null;
		try {
			Glog.Log(Glog.LOG_COMMON,"sendXMLDataToClient" ,"---------- start sendXML ------------ ");
			if (sendData == null) {
				Glog.Log(Glog.LOG_ERROR,"sendXMLDataToClient" ,"sendData is null!!!");
			}
			oos = new ObjectOutputStream(sock.getOutputStream());
			oos.writeObject(sendData);
			oos.flush();	
			
			oos.close();
			sock.close();
			
		} catch (Exception e) {
			// TODO: handle exception
			Glog.Log(Glog.LOG_ERROR,"sendXMLDataToClient" , e.toString());
		}
	}
	
	
	
	
	
	
	
	
	/**
	 * 
	 * Desc :
	 * @Method Name : main
	 * @param args
	 *
	 */
	public static void main(String[] args){
		TierServer t = new TierServer();
	}	
}